/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package at.irian.demo.jsfatwork.service;

import at.irian.demo.jsfatwork.domain.Group;
import at.irian.demo.jsfatwork.domain.User;
import at.irian.demo.jsfatwork.repository.GenericRepository;
import at.irian.demo.jsfatwork.repository.GroupRepository;
import at.irian.demo.jsfatwork.repository.UserRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.inject.Inject;
import java.util.List;

/**
 * @author JSF@Work Project Team
 */
@Service
public class DefaultGroupService extends AbstractGenericService<Group> implements GroupService
{
    private GroupRepository groupRepository;
    private UserRepository userRepository;

    //needed for creating proxies
    protected DefaultGroupService()
    {
    }

    @Inject
    public DefaultGroupService(GroupRepository groupRepository, UserRepository userRepository)
    {
        this.groupRepository = groupRepository;
        this.userRepository = userRepository;
    }

    protected GenericRepository<Group> getRepository()
    {
        return this.groupRepository;
    }

    public List<Group> findSubscribedGroups(User user)
    {
        return this.groupRepository.loadAllFor(user);
    }

    public List<Group> findUnSubscribedGroups(User user)
    {
        return this.groupRepository.loadUnSubscribedGroups(user);
    }

    @Transactional
    public void subscribe(String userName, Group group)
    {
        User user = this.userRepository.loadUser(userName);
        group.addUser(user);
        this.groupRepository.save(group);
    }

    @Transactional
    public void unsubscribe(String userName, Group group)
    {
        User user = this.userRepository.loadUser(userName);
        group.removeUser(user);
        this.groupRepository.save(group);
    }
}